package com.systop.ltbook.notes.webapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.systop.cms.utils.PageUtil;
import com.systop.common.modules.security.user.LoginUserService;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.dao.support.Page;
import com.systop.core.webapp.struts2.action.DefaultCrudAction;
import com.systop.ltbook.notes.model.Notes;
import com.systop.ltbook.notes.service.NotesManager;

@SuppressWarnings("serial")
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class NotesAction extends DefaultCrudAction<Notes, NotesManager> {

	public String title;

	public Date strDate;

	public Date endDate;

	private Integer pageSize = 10;
	
	/**
	 * 登陆用户信息管理
	 */
	@Autowired
	private LoginUserService loginUserService;

	/**
	 * 存储创建时间
	 */
	public String save() {
		User user = loginUserService.getLoginUser(getRequest());
		if (user != null){
			if (getModel().getId() == null) {
				getModel().setUser(user);
				getModel().setCreateDate(new Date());
			}
			return super.save();
		}else{
			addActionError("用户未登录");
			return INPUT;
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String index() {
		User user = loginUserService.getLoginUser(getRequest());
		if (user !=null ){
			List args = new ArrayList();
			StringBuffer hql = new StringBuffer("from Notes n where n.user.id = ?");
			args.add(user.getId());
			if (StringUtils.isNotBlank(title)) {
				hql.append(" and n.title like ?");
				args.add("%" + title + "%");
			}
			if (strDate != null && endDate != null) {
				hql.append(" and (n.createDate between ? and ?)");
				args.add(strDate);
				args.add(endDate);
			}
			hql.append(" order by n.createDate desc");
			Page page = PageUtil.getPage(getPageNo(), pageSize);
			page = getManager().pageQuery(page, hql.toString(), args.toArray());
			getRequest().setAttribute("page", page);
		}
		return INDEX;
	}
	
	protected int getPageNo(){
		String pNo = getRequest().getParameter("pageNo");
		int pageNo = 1;
		if (StringUtils.isNumeric(pNo)){
			pageNo = Integer.parseInt(pNo);
		}
		return pageNo;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public Date getStrDate() {
		return strDate;
	}

	public void setStrDate(Date strDate) {
		this.strDate = strDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}
}
